package com.apestech.api.condition;

import com.apestech.formwork.condition.ConditionUtil;
import com.apestech.framework.db.SqlResultSet;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.callback.QueryCallBackHandler;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.SqlUtil;
import com.apestech.framework.sql.modul.FromList;
import com.apestech.framework.util.FileUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.xml.condition.modul.ConditionStrategy;

import java.io.File;
import java.util.ArrayList;

public class ConditionTcTool {
    private SqlSession session;
    private ConditionStrategyExec exec;
    private ConditionStrategy conditionStrategy;
    private String conditionStrategyId;
    private String dateStr;

    private JSONObject keyjson;  //单张单据跑
    private JSONObject datejson;  //时间段跑



    public ConditionTcTool(SqlSession session){
        this.session=session;
        keyjson=new JSONObject();
        keyjson.put("TC_XSTC_SK_ZD","A.DATE_DONE");
        keyjson.put("TC_XSTC_SK_FD","A.DATE_DONE");
        keyjson.put("TC_FXXSTC_SK_FDS","A.DATE_DONE");
        keyjson.put("TC_FXXSTC_SK_DS","A.DATE_DONE");
        keyjson.put("TC_DSXSTC_SK","C.CREATE_DATE");
        keyjson.put("TC_FXDJSGTC_SK_FDS","A.DATE_DONE");
        keyjson.put("TC_FXDJSGTC_SK_DS","A.DATE_DONE");
        keyjson.put("TC_JSCTC_SK_JC","(SELECT T.OPERATE_DATE FROM FN_INNER_PICK_DEL_UP_CAR_ITEM T WHERE T.INNER_PICK_DELIVERY_UP_CAR = B.ID AND T.NODE_DESCRIPTION = 'confirm')");
        keyjson.put("TC_JSCTC_SK_GH","(SELECT T.OPERATE_DATE FROM FN_INNER_PICK_DEL_UP_CAR_ITEM T WHERE T.INNER_PICK_DELIVERY_UP_CAR = B.ID AND T.NODE_DESCRIPTION = 'confirm')");
        keyjson.put("TC_KDTC_SK","(SELECT T.OPERATE_DATE FROM FN_INNER_PICK_DEL_UP_CAR_ITEM T WHERE T.INNER_PICK_DELIVERY_UP_CAR = B.ID AND T.NODE_DESCRIPTION = 'confirm')");
        keyjson.put("TC_YYKDTC_SK_ZD","A.DATE_DONE");
        keyjson.put("TC_YYKDTC_SK_FD","A.DATE_DONE");
        keyjson.put("TC_NKTC_SK_YTB","A.DATE_DONE");
        keyjson.put("TC_NKTC_SK_WTB","A.DATE_DONE");
        keyjson.put("TC_CXTC_SK","A.RECEIPT_DATE");
        //keyjson.put("TC_MLZETC_SK","A.RECEIPT_DATE");
        keyjson.put("TC_DJSGTC_SK_ZD","A.DATE_DONE");
        keyjson.put("TC_DJSGTC_SK_FD","A.DATE_DONE");
        keyjson.put("TC_DSGZTC_SK_ZD","C.DATE_APPROVE");
        keyjson.put("TC_DSGZTC_SK_FD","C.DATE_APPROVE");
        keyjson.put("TC_DKTC_SK_WCDK","A.LAST_UPDATED_STAMP");
        keyjson.put("TC_DKTC_SK_DSWC","A.DATE_DONE");

        datejson=new JSONObject();
        datejson.put("OLD_VIP_SURPLUS_SP_SK", "1");
    }

    public void setInfo(String conditionStrategyId, String dateStr) throws Exception {
        this.conditionStrategyId=conditionStrategyId;
        this.dateStr=dateStr;
        if(this.dateStr==null){
            String str=keyjson.getString(conditionStrategyId);
            if(str!=null){
                this.dateStr=str;
            }
        }
        exec=new ConditionStrategyExec(session, this.conditionStrategyId);
        conditionStrategy=exec.getConditionStrategy();
    }

    public void exec(JSONObject input) throws Exception {
        exec.setInput(input);
        exec.expain();
        System.out.println(JSON.toJSONString(exec.getResultMap()));
    }

    public ArrayList<String> getStartSql() throws Exception {
        ArrayList<String> sqllist=new ArrayList<String>();
        ArrayList<ConditionStrategy.Step> list=conditionStrategy.getSteps();
        ConditionStrategy.Step step=null;
        int len=list.size();
        for(int i=0; i<len; i++){
            step=list.get(i);
            if("while".equals(step.getType())){
                if(step.getFwhile().getSql().getSql().indexOf("#{BILL_ID}")<0){
                    continue;
                }
                String from=step.getFwhile().getSql().getFrom();
                String sqlfrom=step.getFwhile().getSql().getSqlfrom();
                String sumId=step.getFwhile().getSql().getSumId();
                String wsql=step.getFwhile().getSql().getSql();
                String sql=getSql(wsql, from, sqlfrom, sumId);
                sqllist.add(sql);
            }
        }
        return sqllist;
    }

    private String getSql(String osql, String ofrom, String sqlfrom, String sumId) throws Exception {
        String sql=osql;  //.toUpperCase();
        String from=ofrom; //.toUpperCase();
        String sub="";
        int spos=-1;
        int pos=-1;
        if(sqlfrom==null){
            FromList fromlist=new FromList(from, null, session);
            ArrayList<SqlUtil.From> flist=fromlist.getForm(from);
            int len=flist.size();
            SqlUtil.From sfrom=flist.get(0);
            SqlUtil.From efrom=flist.get(len-1);
            spos=sql.lastIndexOf(sfrom.getTab()+" ");  //countString(sql, sfrom.getTab());
            int epos=sql.indexOf(efrom.getTab()+" ", spos);  //countString(sql, efrom.getTab());
            //sub=sql.substring(spos, epos+efrom.getTab().length());
            pos=sql.substring(0, spos).lastIndexOf("FROM");
            sub=sql.substring(pos, sql.length());
        } else {
            pos=sql.indexOf(sqlfrom);
            sub=sql.substring(pos, sql.length());
        }

        if(!"".equals(sub)){
            String ssub;
            pos=sub.indexOf("#{BILL_ID}");
            spos=sub.lastIndexOf("AND", pos);
            if(sumId==null){
                ssub=sub.substring(spos+3, pos);
                ssub=ssub.replace("=","");
                ssub=ssub.replace(" ","");
            } else {
                ssub=sumId;
            }
            String str="SELECT "+ssub+" "+sub.substring(0, spos);
            str=str+" AND "+dateStr+" >= #{DATE_START} AND "+dateStr+" < #{DATE_END}";
            str=str+sub.substring(pos+"#{BILL_ID}".length(), sub.length());
            sub=str;
        }
        return sub;
    }

    public void execAllData(boolean exec, JSONObject input, String sid) throws Exception {
        execAllData(exec, input, sid, "con_Employee_Commission.xml");
//        execAllData(exec, input, sid, "vip_surplus.xml");
    }

    public void execAllData(boolean exec, JSONObject input, String sid, String fileName) throws Exception {
        String path= LocalVariable.getRootDir()+"condition"+ File.separator;
        if(FileUtil.isFileExist(path+session.getTheme()+File.separator)){
            path=path+session.getTheme()+File.separator;
        }
        path=path+fileName;
        ArrayList<String> flist= ConditionUtil.getFileTypeIdList(session, path, "conditionStrategyDef");
        int len=flist.size();
        for(int i=0; i<len; i++){
            String id=flist.get(i);
            if(sid!=null && id.indexOf(sid)!=0){
                continue;
            }
            if(datejson.get(id)!=null){
                System.out.println("日期方式直接执行："+id);
                if(exec){
                    ConditionTcTool tool=new ConditionTcTool(session);
                    tool.setInfo(id, null);
                    tool.exec(input);
                }
            } else {
                String from=hasWhile(id);
                if(from!=null){
                    System.out.println(id);
                    ConditionTcTool tool=new ConditionTcTool(session);
                    tool.setInfo(id, null);
                    //ArrayList<String> slist=tool.getStartSql();
                    //System.out.println(JSON.toJSONString(slist));
                    String sql=tool.getStartSql().get(0);
                    if(exec){
                        input.put("autoCompletion","0");
                        input.put("nb_from", from);
                        session.getForResultSet().sql(sql, input, new QueryCallBackHandler(){
                            @Override
                            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                                while(rs.next()){
                                    tool.exec(rs.toRowJson());
                                }
                            }
                        });
                    }
                }
            }

        }
    }

    private String hasWhile(String id) throws Exception {
        ConditionStrategy strategy= ConditionUtil.getConditionStrategy(id, session);
        ArrayList<ConditionStrategy.Step> list=strategy.getSteps();
        ConditionStrategy.Step step=null;
        int len=list.size();
        for(int i=0; i<len; i++){
            step=list.get(i);
            if("while".equals(step.getType())){
                String sql=step.getFwhile().getSql().getSql();
                if(sql.indexOf("#{BILL_ID}")>=0){
                    return step.getFwhile().getSql().getFrom();
                }
            }
        }
        return null;
    }

}
